const Url2File = {
    imgUrlToFile(url,callback) {
        var self = Url2File;
        var imgLink = url + '?a=' + Math.floor(Math.random()*10000000);
        var tempImage = new Image();
        console.log(0)
        console.log(url)
        //如果图片url是网络url，要加下一句代码
        tempImage.crossOrigin = "*";
        tempImage.referrerpolicy = 'no-referrer'
        tempImage.onload = function() {
            console.log(1)
          var base64 = self.getBase64Image(tempImage);
          console.log(base64)
          var imgblob = self.base64toBlob(base64);
          console.log('imgblob:',imgblob)
          var filename = self.getFileName(imgLink);
          console.log('filename:',filename)
          callback(self.blobToFile(imgblob, filename));
          console.log(5)
        };
        tempImage.src = imgLink;
      },
      getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
        var dataURL = canvas.toDataURL("image/" + ext);
        return dataURL;
      },
      base64toBlob(base64) {
        let arr = base64.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      },
      blobToFile(blob, filename) {
        // edge浏览器不支持new File对象，所以用以下方法兼容
        blob.lastModifiedDate = new Date();
        blob.name = filename;
        return blob;
      },
      getFileName(url) {
        // 获取到文件名
        let pos = url.lastIndexOf("/"); // 查找最后一个/的位置
        var str = url.substring(pos + 1);
        str = str.substring(0,str.length-10);
        return str; // 截取最后一个/位置到字符长度，也就是截取文件名
      },
      getBaseFileName(url) {
        // 获取到文件名
        let pos = url.lastIndexOf("/"); // 查找最后一个/的位置
        var str = url.substring(pos + 1);
        return str; // 截取最后一个/位置到字符长度，也就是截取文件名
      }
}

export default Url2File